import {AsyncStorage} from 'react-native'
import Request from "../utils/Request";
import {AuthModel} from "../interface/index";

const STORAGE_KEY = "STORAGE_KEY_balance";
export default {
    namespace: 'balance',
    state: {
        loading:false,
        incomeList:[],
        withDrawList:[],
    },
    reducers: {
        save(state, {payload}) {
            return {...state, ...payload}
        }
    },
    effects: {
        //保存到本地
        * saveToStorage({payload}, {call}) {
            yield call(AsyncStorage.setItem, STORAGE_KEY, JSON.stringify(payload))
        },
        //本地恢复
        * restoreFromStorage({payload}, {call, put, select}) {
            const data = yield call(AsyncStorage.getItem, STORAGE_KEY);
            yield put({
                type: 'save',
                payload: {...JSON.parse(data)}
            });
        },

//收入列表
        *fetchInclomeList({payload},{call,put,select}){
            yield put({
                type:'save',
                payload:{loading:true}
            });

            const auth:AuthModel = yield select(state=>state.auth);
            const  data = yield call(Request.get,Request.getApi().incomeList,{store_Id:auth.profile.id,...payload});
            yield put({
                type:'save',
                payload:{loading:false}
            });
            if(data){
                yield put({
                    type:'save',
                    payload:{incomeList:data.data}
                })
            }
        },
        //支出列表
        *fetchWithDrawList({payload},{call,put,select}){
            yield put({
                type:'save',
                payload:{loading:true}
            });

            const auth:AuthModel = yield select(state=>state.auth);
            const  data = yield call(Request.get,Request.getApi().withdrawList,{store_Id:auth.profile.id,...payload});
            yield put({
                type:'save',
                payload:{loading:false}
            });
            if(data){
                yield put({
                    type:'save',
                    payload:{withDrawList:data.data}
                })
            }
        }
    },
    subscriptions: {
        setup({dispatch}) {

        }
    },
};
